package com.example.daxiguaforharmony.utils;

import ohos.app.Context;
import ohos.app.Environment;
import ohos.media.audio.*;
import ohos.media.common.Source;
import ohos.media.player.Player;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class Audio  {
    public static final int VLOMUN_STEP = 1;

    private static Audio _instance = null;
    public static Audio getInstance() {
        if (_instance == null) {
            synchronized (Audio.class) {
                if (_instance == null) _instance = new Audio();
            }
        }
        return _instance;
    }

    private Context context = null;
    private AudioManager audioManager = null;
    private Player soundPlayer = null;
    private Map<String, Source> audioSources = null;
    private String audioCachePath = null;

    private Audio() {
    }

    public void init(Context context) {
        this.context = context;
        if (this.audioManager == null) {
            this.audioManager = new AudioManager(context);
        }
        if (this.audioSources == null) {
            this.audioSources = new HashMap<String, Source>();
        }
        if (this.audioCachePath == null) {
            File file = this.context.getExternalFilesDir(Environment.DIRECTORY_MUSIC);
            this.audioCachePath = file.getPath();
        }
        if (this.soundPlayer == null) {
            this.soundPlayer = new Player(context);
        }
    }

    public boolean vloumnUp(){
        try {
            int volume = audioManager.getVolume(AudioManager.AudioVolumeType.STREAM_MUSIC);
            return  audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, volume + VLOMUN_STEP);

        } catch (AudioRemoteException e) {
            e.printStackTrace();
        }
        return false;
    }
    public boolean vloumnDown(){
        try {
            int volume = audioManager.getVolume(AudioManager.AudioVolumeType.STREAM_MUSIC);
            return  audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, volume - VLOMUN_STEP);

        } catch (AudioRemoteException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void preloadAudio(String[] audioPaths, boolean cacheSource) {
        try {
            for (int i = 0; i < audioPaths.length; i++) {
                File mp3File = new File(this.audioCachePath + "/" + audioPaths[i]);
                System.out.println("mp3File==="+mp3File.getAbsolutePath());
                if(!mp3File.exists()) {
                    String filePath = String.format("assets/entry/resources/rawfile/%s", audioPaths[i]);
                    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
                    FileUtils.copyFileUsingFileStreams(inputStream, mp3File);
                    LogUtil.info(Audio.class.getName(), "MP3写入缓存目录, 路径:=== " + filePath);
                }

                String mp3Path = mp3File.getAbsolutePath();
                LogUtil.info(Audio.class.getName(), "MP3缓存路径:=== " + mp3Path);

                // 预处理音效实例
                if (cacheSource == true) {
                    FileInputStream fileInputStream = new FileInputStream(mp3File);
                    FileDescriptor fileDescriptor = fileInputStream.getFD();
                    Source source = new Source(fileDescriptor);
                    this.audioSources.put(audioPaths[i], source);
                }
            }
        } catch (FileNotFoundException ex) {
            LogUtil.info(Audio.class.getName(), ex.getMessage());
            ex.printStackTrace();
        } catch (IOException ex) {
            LogUtil.info(Audio.class.getName(), ex.getMessage());
            ex.printStackTrace();
        }
    }

    public void playAudio(String audioPath) {
        Source source = null;
        if (this.audioSources.containsKey(audioPath)) {
            source = this.audioSources.get(audioPath);
        } else {
            try {
                File mp3File = new File(this.audioCachePath + "/" + audioPath);
                FileInputStream fileInputStream = new FileInputStream(mp3File);
                FileDescriptor fileDescriptor = fileInputStream.getFD();
                source = new Source(fileDescriptor);
            } catch (IOException e) {
                LogUtil.error(Audio.class.getName(), e.getMessage());
                e.printStackTrace();
            }
        }
        if (source == null) {
            LogUtil.error(Audio.class.getName(), "playAudio: error resPath = " + audioPath);
            return;
        }
        System.out.println("playAudio start ==="+audioPath);
        this.soundPlayer.setSource(source);
        this.soundPlayer.prepare();
        this.soundPlayer.play();
        System.out.println("playAudio end ==="+audioPath);
    }

    public void playAudio(int resID)  {
        try {
            // 步骤1：实例化对象
            SoundPlayer soundPlayer = new SoundPlayer(AudioManager.AudioVolumeType.STREAM_MUSIC.getValue());
            // 步骤2：指定音频资源加载并创建短音
            int soundId = soundPlayer.createSound(context,resID);
            // 步骤3：指定音量，循环次数和播放速度
            SoundPlayer.SoundPlayerParameters parameters = new SoundPlayer.SoundPlayerParameters();
            parameters.setLoop(1);
            parameters.setSpeed(1.0f);
            // 步骤4：短音播放
            soundPlayer.play(soundId, parameters);
            // 步骤5：停止播放
            //soundPlayer.stop(soundId);
            //步骤6：释放短音资源
            // soundPlayer.deleteSound(soundId);
        } catch (Exception ex) {
            LogUtil.info("PlayAbility", ex.getMessage());
            System.out.println("====="+ex.getMessage());
            ex.printStackTrace();
        }
    }

    public void testDir() {
        File getFilesDir = context.getFilesDir();
        System.out.println("私有getFilesDir路径===: " + getFilesDir);
        File getDataDir = context.getDataDir();
        System.out.println("私有getDataDir路径===: " + getDataDir);
        File mp3FilePath = context.getExternalFilesDir(Environment.DIRECTORY_MUSIC);
        System.out.println("私有mp3FilePath路径===: " + mp3FilePath);
        String getBundleResourcePath = context.getBundleResourcePath();
        System.out.println("私有getBundleResourcePath路径===: " +getBundleResourcePath);
    }

}
